﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;

namespace bridge.Silverlight.Helpers
{
    public class HttpHelper
    {
        public static async Task<T> Post<T>(string url, string val, List<KeyValuePair<string, string>> headersParams = null) where T : class
        {


            var client = new HttpClient();
            var t = default(T);
            using (var request = new HttpRequestMessage())
            {

                var content = new StringContent(val);
                content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                
                
                request.Content = content;                
                request.Method = new HttpMethod("POST");
                request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                if (headersParams != null)
                {
                    foreach (var item in headersParams)
                    {
                        request.Headers.Add(item.Key, item.Value);
                    }
                }
                request.RequestUri = new Uri(url, UriKind.RelativeOrAbsolute);
                var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, CancellationToken.None).ConfigureAwait(false);

                var headers = Enumerable.ToDictionary(response.Headers, h_ => h_.Key, h_ => h_.Value);
                if (response.Content != null && response.Content.Headers != null)
                {
                    foreach (var item_ in response.Content.Headers)
                    {
                        headers[item_.Key] = item_.Value;
                    }
                }

                var status = ((int)response.StatusCode).ToString();
                if (status == "200")
                {
                    var responseData = response.Content == null ? null : await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    t = JsonConvert.DeserializeObject<T>(responseData);
                    return t; ;

                }
            }
            return t;
        }

        /// <summary>
        /// get json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>

        public static async Task<T> Get<T>(string url, List<KeyValuePair<string, string>> headersParams = null) where T : class
        {
            var client_ = new HttpClient();
            try
            {
                using (var request = new HttpRequestMessage())
                {

                    request.Method = new HttpMethod("GET");

                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    if (headersParams != null)
                    {
                        foreach (var item in headersParams)
                        {
                            request.Headers.Add(item.Key, item.Value);
                        }
                    }
                    request.RequestUri = new Uri(url, UriKind.RelativeOrAbsolute);
                    var reponse = await client_.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, CancellationToken.None).ConfigureAwait(false);
                    try
                    {
                        var headers_ = Enumerable.ToDictionary(reponse.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (reponse.Content != null && reponse.Content.Headers != null)
                        {
                            foreach (var item_ in reponse.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }
                        var status = ((int)reponse.StatusCode).ToString();
                        if (status == "200")
                        {

                            var reponseData = reponse.Content == null ? null : await reponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                            if (typeof(T) == typeof(string))
                            {
                                return reponseData as T;
                            }
                            else
                            {
                                return JsonConvert.DeserializeObject<T>(reponseData);
                            }
                        }
                        else
                        if (status != "200" && status != "204")
                        {
                            var responseData_ = reponse.Content == null ? null : await reponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                            throw new Exception(responseData_);
                        }
                        return default(T);
                    }
                    finally
                    {
                        if (reponse != null)
                        {
                            reponse.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (client_ != null)
                    client_.Dispose();
            }
        }
    }
}
